from sko.DE import DE
import numpy as np


def getweight(w3):
    # w3(3行x7列）
    def obj_func(p):

        # w1 = w; w2 = w; w3 = w; w4 = w; w5 = w; w6 = w; w7 = w;
        # w8 = w;  #参数a1
        # w9 = w;  #参数a2
        # w10 = w; #参数a3
        x1, x2, x3, x4, x5, x6, x7, x8, x9, x10 = p

        return x8 * ((x1-w3[0, 0]) ** 2 + (x2-w3[0, 1]) ** 2 + (x3-w3[0, 2]) ** 2
                     + (x4-w3[0, 3]) ** 2 + (x5-w3[0, 4]) ** 2 + (x6-w3[0, 5]) ** 2 + (x7-w3[0, 6]) ** 2) \
               + x9 * ((x1-w3[1, 0]) ** 2 + (x2-w3[1, 1]) ** 2 + (x3-w3[1, 2]) ** 2
                     + (x4-w3[1, 3]) ** 2 + (x5-w3[1, 4]) ** 2 + (x6-w3[1, 5]) ** 2 + (x7-w3[1, 6]) ** 2)\
               + x10 * ((x1-w3[2, 0]) ** 2 + (x2-w3[2, 1]) ** 2 + (x3-w3[2, 2]) ** 2
                     + (x4-w3[2, 3]) ** 2 + (x5-w3[2, 4]) ** 2 + (x6-w3[2, 5]) ** 2 + (x7-w3[2, 6]) ** 2)

    constraint_eq = [
        lambda x: 1 - x[0] - x[1] - x[2] - x[3] - x[4] - x[5] - x[6],
        lambda x: 1 - x[7] - x[8] - x[9]
    ]

    constraint_ueq = [
        lambda x: 1 - x[0] * x[1],
        lambda x: x[0] * x[1] - 5
    ]

    # %% Do DifferentialEvolution
    # de = DE(func=obj_func, n_dim=10, size_pop=50, max_iter=800, lb=[0, 0, 0,0,0,0,0,0,0,0], ub=[1, 1, 1,1,1,1,1,1,1,1],
    #       constraint_eq=constraint_eq, constraint_ueq=constraint_ueq)
    # de = DE(func=obj_func, n_dim=10 , size_pop=50, max_iter=800, lb=[0, 0, 0,0,0,0,0,0,0,0], ub=[1, 1, 1,1,1,1,1,1,1,1],
    #       constraint_eq='', constraint_ueq=constraint_ueq)

    de = DE(func=obj_func, n_dim=10, size_pop=15, max_iter=8000, lb=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ub=[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
            constraint_eq=constraint_eq, constraint_ueq='')
    # lb为变量的取值下限，ub为变量的取值上限

    best_x, best_y = de.run()
    return np.concatenate((best_x, best_y))



